package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.lab.LabInstrSetup;
import com.ysd.lis.entity.lab.LabRptCampusArea;
import com.ysd.lis.entity.lab.LabRptGroup;
import com.ysd.lis.mapper.lab.LabInstrSetupMapper;
import com.ysd.lis.mapper.lab.LabRptGroupMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.AddRptGroupParam;
import com.ysd.lis.request.RptGroupInstrDto;
import com.ysd.lis.request.RptGroupPageParam;
import com.ysd.lis.request.lab.RptCampusParam;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.lab.LabInstrSetupService;
import com.ysd.lis.service.lab.LabRptGroupService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
public class LabRptGroupServiceImpl extends ServiceImpl<LabRptGroupMapper, LabRptGroup> implements LabRptGroupService {

    @Autowired
    private LabRptGroupMapper labRptGroupMapper;

    @Autowired
    private LabInstrSetupMapper labInstrSetupMapper;

    @Autowired
    private LabInstrSetupService labInstrSetupService;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;

    @Autowired
    SysInterfaceMapper sysInterfaceMapper;


    @Override
    public Result findRptGroup(String keywords) {
        LambdaQueryWrapper<LabRptGroup> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(LabRptGroup::getDelFlag, 0);
        if (StringUtils.isNotBlank(keywords)) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabRptGroup::getRptGroupName, keywords).or().like(LabRptGroup::getRptGroup, keywords));
        }
        List<LabRptGroup> reportGroupEntities = labRptGroupMapper.selectList(lambdaQueryWrapper);

        List<Map<String, Object>> jygzz = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("JYGZZ").getData();
        List<LabRptGroup> collect = reportGroupEntities.stream().map(labRptGroup -> {
            try {
                String str = jygzz.stream().filter(a -> a.get("code").equals(StringUtils.isNotBlank(labRptGroup.getWorkGroup()) ? labRptGroup.getWorkGroup() : "!@#123#@!")).findFirst().get().get("name").toString();
                Integer sx = Integer.parseInt(jygzz.stream().filter(a -> a.get("code").equals(StringUtils.isNotBlank(labRptGroup.getWorkGroup()) ? labRptGroup.getWorkGroup() : "!@#123#@!")).findFirst().get().get("sx").toString());

                labRptGroup.setDictName(str);
                labRptGroup.setSx(sx);
            } catch (Exception exception) {
                //TODO
            }
            return labRptGroup;
        }).collect(Collectors.toList());
        List<LabRptGroup> collect1 = reportGroupEntities.stream().sorted(Comparator.comparing(l -> l.getSx(), Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());

        return Result.succ(1, "查询成功！", collect1);
    }

    @Override
    public Result findPoctRptGroup() {
        LambdaQueryWrapper<LabRptGroup> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(LabRptGroup::getDelFlag, 0);
        lambdaQueryWrapper.eq(LabRptGroup::getPoct,"1");
        List<LabRptGroup> reportGroupEntities = labRptGroupMapper.selectList(lambdaQueryWrapper);

        List<Map<String, Object>> jygzz = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("JYGZZ").getData();
        List<LabRptGroup> collect = reportGroupEntities.stream().map(labRptGroup -> {
            try {
                String str = jygzz.stream().filter(a -> a.get("code").equals(StringUtils.isNotBlank(labRptGroup.getWorkGroup()) ? labRptGroup.getWorkGroup() : "!@#123#@!")).findFirst().get().get("name").toString();
                Integer sx = Integer.parseInt(jygzz.stream().filter(a -> a.get("code").equals(StringUtils.isNotBlank(labRptGroup.getWorkGroup()) ? labRptGroup.getWorkGroup() : "!@#123#@!")).findFirst().get().get("sx").toString());

                labRptGroup.setDictName(str);
                labRptGroup.setSx(sx);
            } catch (Exception exception) {
                //TODO
            }
            return labRptGroup;
        }).collect(Collectors.toList());
        List<LabRptGroup> collect1 = reportGroupEntities.stream().sorted(Comparator.comparing(l -> l.getSx(), Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());

        return Result.succ(1, "查询成功！", collect1);
    }

    @Override
    public Result addRptGroup(AddRptGroupParam addRptGroupParam) {
        LabRptGroup reportGroup = new LabRptGroup();
        BeanUtil.copyProperties(addRptGroupParam, reportGroup);
        boolean save = this.save(reportGroup);
        if (save) {
            return Result.succ(1, "添加成功！", reportGroup);
        } else {
            return Result.fail("添加失败！");
        }
    }

    @Override
    public Result editRptGroup(LabRptGroup reportGroup) {
        // ReportUnitEntity reportUnit=new ReportUnitEntity();
        // BeanUtil.copyProperties(addReportUnitParam,reportUnit);
        int update = labRptGroupMapper.updateById(reportGroup);
        if (update > 0) {
            return Result.succ(1, "编辑成功！", reportGroup);
        } else {
            return Result.fail("编辑失败！");
        }
    }

    @Override
    public Result deleteRptGroup(LabRptGroup reportGroup) {

        int delete = labRptGroupMapper.deleteById(reportGroup.getId());
        if (delete > 0) {
            return Result.succ(1, "删除成功！", null);
        } else {
            return Result.fail("删除失败！");
        }
    }

    @Override
    public Result getRptGroupPageList(RptGroupPageParam pageParam) {
        Page<LabRptGroup> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        LambdaQueryWrapper<LabRptGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabRptGroup::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getKeyWords())) {
            lambdaQueryWrapper.and(wrapper ->
                    wrapper.like(LabRptGroup::getRptGroupName, pageParam.getKeyWords())
                            .or()
                            .like(LabRptGroup::getRptGroup, pageParam.getKeyWords())
                            .or()
                            .like(LabRptGroup::getInputCode, pageParam.getKeyWords())
            );
        }
        if (StringUtils.isNotBlank(pageParam.getBusinessType())) {
            lambdaQueryWrapper.eq(LabRptGroup::getBusinessType, pageParam.getBusinessType());
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(pageParam.getOrgId()), LabRptGroup::getOrgId, pageParam.getOrgId());
        lambdaQueryWrapper.orderByAsc(LabRptGroup::getSeq);
        Page<LabRptGroup> reportGroupEntityPage = labRptGroupMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", reportGroupEntityPage);
    }

    @Override
    public Result findRptGroupSimple(String id) {
        LabRptGroup labRptGroup = labRptGroupMapper.selectById(id);
        return Result.succ(1, "查询成功", labRptGroup);
    }

    @Override
    public Result findInstrByRptGroupId(String id) {
        LambdaQueryWrapper<LabInstrSetup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabInstrSetup::getDelFlag, 0).eq(LabInstrSetup::getRptGroup, id);
        List<LabInstrSetup> instrSetups = labInstrSetupMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", instrSetups);
    }

    @Override
    public Result getRptGroupList(RptGroupPageParam pageParam) {
        LambdaQueryWrapper<LabRptGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabRptGroup::getDelFlag, 0);
        if (StrUtil.isNotEmpty(pageParam.getKeyWords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabRptGroup::getRptGroupName, pageParam.getKeyWords()).or().like(LabRptGroup::getRptGroup, pageParam.getKeyWords()));
        }
        lambdaQueryWrapper.eq(StrUtil.isNotEmpty(pageParam.getOrgId()), LabRptGroup::getOrgId, pageParam.getOrgId());
        if (StringUtils.isNotBlank(pageParam.getBusinessType())) {
            lambdaQueryWrapper.eq(LabRptGroup::getBusinessType, pageParam.getBusinessType());
        }
        List<LabRptGroup> reportGroupEntities = labRptGroupMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", reportGroupEntities);
    }

    @Override
    public Result findInstrsByRptGroupId(RptGroupPageParam param) {
        LambdaQueryWrapper<LabInstrSetup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabInstrSetup::getDelFlag, 0).
                and(wrapper -> wrapper.isNull(LabInstrSetup::getRptGroup).or().ne(LabInstrSetup::getRptGroup, param.getId()));
        if (StringUtils.isNotBlank(param.getKeyWords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabInstrSetup::getInstrCode, param.getKeyWords())
                    .or().like(LabInstrSetup::getInstrName, param.getKeyWords())
                    .or().like(LabInstrSetup::getInstrMark, param.getKeyWords())
                    .or().like(LabInstrSetup::getInstrCalled, param.getKeyWords())
                    .or().like(LabInstrSetup::getInputCode, param.getKeyWords()));
        }
        List<LabInstrSetup> instrSetups = labInstrSetupMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", instrSetups);
    }

    @Override
    public Result batchAddInstrList(RptGroupInstrDto dto) {
        List<LabInstrSetup> instrSetups = dto.getInstrSetupList();
        boolean b = labInstrSetupService.updateBatchById(instrSetups);
        // List<QcInstrItem> qcInstrItemList = dto.getQcInstrItemList();
        //boolean b = this.saveBatch(qcInstrItemList);
        if (b) {
            return Result.succ(1, "添加成功", null);
        } else {
            return Result.fail(400, "添加失败", "");
        }
    }

    @Override
    public Result deleteInstr(LabInstrSetup labInstrSetup) {
        int i = labInstrSetupMapper.updateById(labInstrSetup);
        return Result.succ(1, "", "");
    }

    @Override
    public Result findRptGroupList(RptGroupPageParam pageParam) {
        LambdaQueryWrapper<LabRptGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabRptGroup::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getKeyWords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabRptGroup::getRptGroupName, pageParam.getKeyWords()).or().like(LabRptGroup::getRptGroup, pageParam.getKeyWords()));
        }
        if (StringUtils.isNotBlank(pageParam.getBusinessType())) {
            lambdaQueryWrapper.eq(LabRptGroup::getBusinessType, pageParam.getBusinessType());
        }
        lambdaQueryWrapper.orderByAsc(LabRptGroup::getSeq);
        List<LabRptGroup> labRptGroups = labRptGroupMapper.selectList(lambdaQueryWrapper);

        List<Map<String, Object>> jygzz = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("JYGZZ").getData();
        List<LabRptGroup> collect = labRptGroups.stream().map(labRptGroup -> {
            try {
                Map<String, Object> jygzzMapObj = jygzz.stream().filter(a -> a.get("code").equals(StringUtils.isNotBlank(labRptGroup.getWorkGroup()) ? labRptGroup.getWorkGroup() : "!@#123#@!")).findFirst().orElse(null);
                if(ToolsUtils.isNotEmpty(jygzzMapObj)){
                    String str = jygzzMapObj.get("name").toString();
                    labRptGroup.setDictName(str);
                    Integer sx = Integer.parseInt(jygzzMapObj.get("sx").toString());
                    labRptGroup.setSx(sx);
                }else {
                    labRptGroup.setDictName(labRptGroup.getWorkGroup());
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return labRptGroup;
        }).collect(Collectors.toList());
        List<LabRptGroup> collect1 = labRptGroups.stream().sorted(Comparator.comparing(l -> l.getSx(), Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        return Result.succ(1, "查询成功", collect1);
    }

    @Override
    public Result syncRptGroups() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);

        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        try {
            if (CollectionUtils.isNotEmpty(collect)) {
                LabRptGroup labRptGroup = new LabRptGroup();
                labRptGroup.setOrgId(orgId);
                for (String webUrl : collect) {
                    String returnMsg = HttpUtil.createPost(webUrl + "/public/syncRptGroup").body(JSONUtil.toJsonStr(labRptGroup)).contentType("application/json").execute().body();
                    JSONObject jsonObject = new JSONObject(returnMsg);
                    JSONObject status = jsonObject.getJSONObject("status");
                    String code = status.get("code").toString();
                    if ("400".equals(code)) {
                        return Result.fail("接口管理平台异常,请检查");
                    }
                }
            }
        } catch (Exception e) {
            return Result.fail("接口管理平台异常,请检查");
        }

        return Result.succ(1, "请求成功", null);
    }

    @Override
    public Result findRptGroupByCampusArea(RptCampusParam param) {
        String keywords = param.getKeywords();
        List<String> campusAreas = param.getCampusAreas();

        MPJLambdaWrapper<LabRptGroup> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabRptGroup.class);
        if(ToolsUtils.isNotEmpty(campusAreas)){
            queryWrapper.innerJoin(LabRptCampusArea.class,"lrc",p->p.eq(LabRptCampusArea::getRptGroup,LabRptGroup::getRptGroup).eq(LabRptCampusArea::getDelFlag,0).in(LabRptCampusArea::getCampusCode,campusAreas));
        }
        queryWrapper.eq(LabRptGroup::getDelFlag, 0);
        if (StringUtils.isNotBlank(keywords)) {
            queryWrapper.and(wrapper -> wrapper.like(LabRptGroup::getRptGroupName, keywords).or().like(LabRptGroup::getRptGroup, keywords));
        }
       List<LabRptGroup> reportGroupEntities = labRptGroupMapper.selectList(queryWrapper);

        List<Map<String, Object>> jygzz = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("JYGZZ").getData();
        List<LabRptGroup> collect = reportGroupEntities.stream().map(labRptGroup -> {
            try {
                String str = jygzz.stream().filter(a -> a.get("code").equals(StringUtils.isNotBlank(labRptGroup.getWorkGroup()) ? labRptGroup.getWorkGroup() : "!@#123#@!")).findFirst().get().get("name").toString();
                Integer sx = Integer.parseInt(jygzz.stream().filter(a -> a.get("code").equals(StringUtils.isNotBlank(labRptGroup.getWorkGroup()) ? labRptGroup.getWorkGroup() : "!@#123#@!")).findFirst().get().get("sx").toString());

                labRptGroup.setDictName(str);
                labRptGroup.setSx(sx);
            } catch (Exception exception) {
                //TODO
            }
            return labRptGroup;
        }).collect(Collectors.toList());
        List<LabRptGroup> collect1 = reportGroupEntities.stream().sorted(Comparator.comparing(l -> l.getSx(), Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());

        return Result.succ(1, "查询成功！", collect1);
    }

    @Override
    public Result getRptGroupPoctList(RptGroupPageParam pageParam) {
        Page<LabRptGroup> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        LambdaQueryWrapper<LabRptGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabRptGroup::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getKeyWords())) {
            lambdaQueryWrapper.and(wrapper ->
                    wrapper.like(LabRptGroup::getRptGroupName, pageParam.getKeyWords())
                            .or()
                            .like(LabRptGroup::getRptGroup, pageParam.getKeyWords())
                            .or()
                            .like(LabRptGroup::getInputCode, pageParam.getKeyWords())
            );
        }
        if (StringUtils.isNotBlank(pageParam.getBusinessType())) {
            lambdaQueryWrapper.eq(LabRptGroup::getBusinessType, pageParam.getBusinessType());
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(pageParam.getOrgId()), LabRptGroup::getOrgId, pageParam.getOrgId());
        lambdaQueryWrapper.eq(LabRptGroup::getPoct,"1");
        lambdaQueryWrapper.orderByAsc(LabRptGroup::getSeq);
        Page<LabRptGroup> reportGroupEntityPage = labRptGroupMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", reportGroupEntityPage);
    }

}
